#include "oGamePreDefine.h"
#include "Actions/oBrickAction.h"
#include "oGameEvent.h"
#include "oGameTypes.h"

oBrickHit::oBrickHit( oUnit* unit ):
oHit(unit)
{
	unit->hp.changed += oPropertyHandler(&oBrickHit::onHpChanged, this);
	_effect->getNode()->setScale(1.5f);
}

void oBrickHit::run()
{
	oModel* model = _owner->getModel();
	int hpIndex = (int)(_owner->hp - 1);
	model->setLook(oNumberStr[hpIndex]);
	CCPoint key = CCPointApplyAffineTransform(_hitPoint, _owner->parentToNodeTransform());
	if (_effect)
	{
		_effect->setOffset(key)->start();
	}
	_owner->setVelocityX(_hitFromRight ? -_attackPower.x : _attackPower.x);
	_owner->setVelocityY(_attackPower.y);
	if (actionStart != NULL)
	{
		actionStart(this);
	}
	if (actionEnd != NULL)
	{
		actionEnd(this);
	}
}

void oBrickHit::onHpChanged( oUnit* owner, float oldValue, float newValue )
{
	if(newValue > 0)
	{
		owner->doIt(ACTION_BRICK_HIT);
	}
	else if (newValue == 0.0f)
	{
		if (_effect)
		{
			_effect->attachTo(_owner->getParent())->setOffset(_hitPoint)->start();
		}
		owner->doIt(ACTION_BRICK_DIE);
	}
}

void oBrickHit::stop()
{
	oAction::stop();
}

oBrickDie::oBrickDie( oUnit* unit ):
oAction(ACTION_BRICK_DIE, oID::PriorityHit+1, unit)
{ }

void oBrickDie::run()
{
	oAction::run();
	_current = 0.0f;
	//_owner->setGroup(GROUP_HIDE);
	_owner->getModel()->runAction(CCEaseBackIn::actionWithAction(CCScaleTo::actionWithDuration(0.3f, 0.0f, 0.0f)));
	if (actionStart != NULL)
	{
		actionStart(this);
	}
}

void oBrickDie::update( ccTime dt )
{
	_current += dt;
	if (_current >= 0.3f)
	{
		oAction::stop();
		if (actionEnd != NULL)
		{
			actionEnd(this);
		}
	}
}